package com.hrc.springboot.component;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginHandlerInterceptor implements HandlerInterceptor {

    // 目标方法执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object user = request.getSession().getAttribute("loginUser");
        if (user == null) { // 从session中取出的对象为空，表示当前网页未登录
            request.setAttribute("msg", "当前页面需要登录之后才可访问");
            // 未登录，请求转发到登录页面
            request.getRequestDispatcher("/index.html").forward(request, response);
            return false;
        } else { // 当前网页已登录
            return true;
        }
    }
}
